Warnings can be helpful when developing, especially if your code will be heavily reused. Here are some examples, but for official documentation on python warnings visit: https://docs.python.org/3.8/library/warnings.html
The default type of a python warning is a UserWarning.
In [1]:
import warnings
def add_int(x,y):
if not isinstance(x,int):
warnings.warn('The x variable type needs to be an int, instead type '+str(type(x))+' was passed')
return None
elif not isinstance(y,int):
warnings.warn('The y variable type needs to be an int, instead type '+str(type(x))+' was passed')
return None
z=x+y
return z
add_int(2,3.0)
You can call other warning types, such as a DeprecationWarning.
In [2]:
class BasicMath:
def add_int(self,x,y):
warnings.warn('The add_int function will be deprecated in a future release, please use the add function.',DeprecationWarning)
if not isinstance(x,int):
warnings.warn('The x variable type needs to be an int, instead type '+str(type(x))+' was passed')
return None
elif not isinstance(y,int):
warnings.warn('The y variable type needs to be an int, instead type '+str(type(x))+' was passed')
return None
z=x+y
return z
def add(self,x,y):
return(x+y)
BasicMath().add_int(2,3.0)
You can choose whether you want to filter out warnings.
In [3]:
import sys
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
print(BasicMath().add_int(2,3.0))
You can also choose to throw warnings as errors.
In [4]:
if not sys.warnoptions:
import warnings
warnings.simplefilter("error")
print(BasicMath().add_int(2,3.0))
In [ ]: